package com.trsj.lnsj.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class UploadHelper {
    public static String handleUploadFile(CommonsMultipartFile imgFile) {
        if (imgFile != null && StringUtils.isNotBlank(imgFile.getName())) {
            String fileName = String.valueOf(System.currentTimeMillis()) + imgFile.getName();
            File file = new File(ConfigurableConstants.getProperty("zlnsj.activity.image.path") + fileName);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            InputStream in = null;
            try {
                in = imgFile.getInputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String filePath=ConfigurableConstants.getProperty("zlnsj.activity.image.path") + fileName;
            if(writeToNewFile(in, filePath)){
                return ConfigurableConstants.getProperty("zlnsj.activity.image.path") + fileName;
            }
        }
        return null;
    }

    /**
     * 读出写出
     * 
     * @param oldFileName
     *            源文件
     * @param newFileName
     *            新文件
     * @throws IOException
     */
    public static boolean writeToNewFile(InputStream in, String newFileName) {
        try {
            FileOutputStream fos = new FileOutputStream(new File(newFileName));
            byte[] bts = new byte[1024];
            int len = 0;
            while ((len = in.read(bts)) != -1) {
                fos.write(bts, 0, len);
            }
            fos.flush();
            fos.close();
            in.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
